<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :show-message="false" label-width="110px">
      <el-card :body-style="{ paddingBottom: '0' }">
        <div slot="header">
          <div class="fw-6 colorY">疾病基础信息</div>
        </div>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="疾病编码" prop="diseaseCode">
              <el-input
                v-model.trim="form.diseaseCode"
                placeholder="请输入"
                :maxLength="12"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="西医疾病" prop="diseaseName" required>
              <el-input
                v-model.trim="form.diseaseName"
                placeholder="请输入"
                :maxLength="12"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="中医疾病" prop="tcmDiseaseName">
              <el-input
                v-model.trim="form.tcmDiseaseName"
                placeholder="请输入"
                :maxLength="12"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="疾病首字母" prop="diseaseFirstLetter">
              <el-input
                v-model.trim="form.diseaseFirstLetter"
                placeholder="不输入则自动生成首字母"
                @blur="pinyinToggle"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="疾病说明" prop="diseaseNote">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入疾病说明"
                v-model="form.diseaseNote"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="疾病辩证路径" prop="syndromeType" required>
              <el-select
                v-model="form.syndromeType"
                placeholder="请选择疾病辩证路径"
                clearable
              >
                <el-option label="中医辨证路径" :value="0"> </el-option>
                <el-option label="贴敷辨证路径" :value="1"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="form.syndromeType === 1" :span="12">
            <el-form-item
              label="适用范围"
              prop="regionCode"
              label-width="130"
              required
            >
              <el-select
                v-model="form.regionCode"
                placeholder="请选择省份"
                clearable
                filterable
              >
                <el-option
                  v-for="item in areaList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="疾病标签" prop="diseaseTag">
              <SelectTag :defaultValue.sync="form.diseaseTag" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="辨证是否开启" prop="syndromeEnable">
              <el-switch
                v-model="form.syndromeEnable"
                :active-value="1"
                active-text="启用"
                :inactive-value="0"
                inactive-text="禁用"
                @change="syndromeToggle"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col v-if="form.syndromeEnable === 0" :span="16">
            <el-form-item label="疾病对应证型" prop="types" required>
              <SelectTCM @change="handTCMChange" />
              <el-tag
                v-for="tcm in tcmList"
                :key="tcm.id"
                size="mini"
                effect="plain"
                class="mr-10"
                >{{ tcm.name }}
              </el-tag>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card
        v-if="form.syndromeEnable !== 0"
        class="mt-15"
        :body-style="{ paddingBottom: '0' }"
      >
        <div slot="header">
          <div class="fw-6 colorY">疾病关联题库</div>
        </div>
        <QuestionBank
          :defaultValue="form.questionnaire"
          @change="updateQuestionnaire"
        />
      </el-card>
      <el-card v-if="form.syndromeEnable !== 0" class="mt-15">
        <div slot="header">
          <div>
            <span class="fw-6 colorY">选项-证型分值设置</span>
            <span class="pl-20 color9 fz-14"
              >证型分值取得分最高者为主,若同等分值取第一列为主</span
            >
          </div>
        </div>

        <el-form-item label="疾病对应证型" prop="types" required>
          <!-- <SearchTCM @change="handTCMChange" /> -->
          <SelectTCM @change="handTCMChange" />
        </el-form-item>

        <el-table :data="form.questionnaire" border>
          <el-table-column label="答案序号" width="200" align="center">
            <template slot-scope="{ row, $index }">
              <div
                v-for="(select, selectIdx) in row.answers"
                :key="selectIdx"
                style="height: 44px; line-height: 44px"
                class="ov-1"
                :class="{ borderB: selectIdx + 1 !== row.answers.length }"
              >
                {{ $index + 1 }}.{{ selectIdx + 1 }} {{ select.answer }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-for="(tcm, tcmIdx) in tcmList"
            :key="tcm.id"
            width="120"
            align="center"
          >
            <template slot="header" slot-scope="scope">
              <div>
                {{ tcm.name }}
                <i
                  class="iconfont el-icon-error"
                  @click="handRemoveTcm(tcmIdx)"
                ></i>
              </div>
            </template>
            <template slot-scope="{ row }">
              <div
                v-for="(select, selectIdx) in row.answers"
                :key="selectIdx"
                style="height: 44px"
                class="disFlxAC"
                :class="{ borderB: selectIdx + 1 !== row.answers.length }"
              >
                <el-input
                  v-if="select.points && select.points[tcmIdx]"
                  size="small"
                  v-model="select.points[tcmIdx].point"
                ></el-input>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-form>

    <div class="tc py-20">
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onSubmit">保存疾病</el-button>
    </div>
  </div>
</template>

<script>
import SelectTag from '../tagList/selectTag'
import SearchTCM from '../tcm/searchTCM'
import SelectTCM from '../tcm/selectTCM'
import QuestionBank from "@/components/QuestionBank";
import { addDisease, updateDisease, getDiseaseDetails, getTCMList } from "@/api/saas/tcm.js";
import { titleToggle } from "@/utils/index";
import pinyin from "js-pinyin";
import { listArea } from "@/api/saas/area";
import { cloneDeep } from "lodash";

export default {
  name: "EditIllness",
  components: {
    SelectTag,
    SearchTCM,
    QuestionBank,
    SelectTCM,
  },
  data() {
    return {
      form: {
        id: undefined,
        diseaseCode: "", // 疾病编码
        diseaseName: "", // 疾病名称
        tcmDiseaseName: "", // 中医疾病名称
        diseaseNote: "", // 疾病简介
        diseaseFirstLetter: "", // 疾病首字母
        syndromeType: 0, // 0-中医辩证,1-贴敷辩证
        regionCode: undefined, // 区域code
        regionName: undefined, // 区域name
        diseaseTag: [], // 疾病标签
        syndromeEnable: 1, // 疾病辩证启用状态: 0不启用 1启用
        types: [], // 证型id集合
        questionnaire: [
          {
            question: "", // 问题
            type: 1, // 1单选2多选
            answers: [
              {
                answer: "", // 答案
              },
            ],
          },
        ],
      },

      tcmList: [], // 证型列表
      areaList: [], // 省份列表
    };
  },
  created() {
    if (this.$route.query.id) {
      getDiseaseDetails(this.$route.query.id).then(res => {
        this.form = res.data;

        if (this.$route.query.type === 'copy') {
          this.form.id = undefined;
        }

        // 获取已选择证型列表-回显
        const ids = res.data.types.join(',');
        getTCMList({ ids, pageSize: res.data.types.length }).then(_r => {
          res.data.types.forEach(id => {
            const item = _r.rows.find(row => row.id === id); // 后端查询返回的顺序不对,需按照types数组的顺序重排
            item && this.tcmList.push(item);
          });
        })
      })
    } else {
      const syndromeType = Number(this.$route.query.syndromeType);
      this.form.syndromeType = syndromeType;
    }
    this.getAreaList();
  },
  methods: {
    // 是否需要辨证切换
    syndromeToggle() {
      if(this.form.syndromeEnable === 0){
        this.tcmList = [];
        this.form.types = [];
        this.form.questionnaire = [{
          question: "默认问题", // 问题
          type: 1, // 1单选2多选
          answers: [
            {
              answer: " ", // 答案
            },
          ],
        }]
      }
    },
    // 证型选择
    handTCMChange(item) {
      if (this.form.syndromeEnable === 0) {
        this.tcmList = [item];
      } else {
        if (this.tcmList.findIndex(v => v.id === item.id) !== -1) {
          this.$message.error(`${item.name} 已经添加过,请勿重复添加`)
          return
        }
        this.tcmList.push(item);
      }
      this.form.types = this.tcmList.map(v => v.id);
      this.updateQuestionnaire();
    },
    handRemoveTcm(index) {
      this.tcmList.splice(index, 1);
      this.form.types = this.tcmList.map(v => v.id);

      this.form.questionnaire.forEach((problem, problemIdx) => {
        problem.answers.forEach((select, selectIdx) => {
          select.points.splice(index, 1);
        })
      })
      this.updateQuestionnaire();
    },
    // 操作题目,选项,证型, 动态改变证型数据
    updateQuestionnaire() {
      this.form.questionnaire.forEach((problem, problemIdx) => {
        problem.answers.forEach((select, selectIdx) => {
          this.$set(select, 'option', `${problemIdx + 1}.${selectIdx + 1}`);
          this.$set(select, 'points', this.tcmList.map((tcm, tcmIdx) => {
            return {
              symptomModelId: tcm.id,
              point: select.points && select.points[tcmIdx] ? select.points[tcmIdx].point : 0
            }
          }))
        })
      });
      console.log(JSON.parse(JSON.stringify(this.form.questionnaire)));
    },
    pinyinToggle() {
      this.form.diseaseFirstLetter = titleToggle(this.form.diseaseFirstLetter);
    },
    // 获取省份列表
    getAreaList() {
      listArea({ level: 1 }).then(res => {
        this.areaList = res.data;
      })
    },
    onSubmit() {
      const that = this;
      that.$refs["form"].validate(async (valid) => {
        if (valid) {
          if (!that.form.diseaseFirstLetter) { // 未填写首字母,自动生成
            let str = pinyin.getCamelChars(that.form.diseaseName);
            that.form.diseaseFirstLetter = titleToggle(str);
          }
          for (let problemIdx = 0; problemIdx < that.form.questionnaire.length; problemIdx++) {
            const problem = that.form.questionnaire[problemIdx];
            if (!problem.question || (problem.answers.findIndex(v => v.answer === "") !== -1)) {
              that.$message.error('问题和选项值不能为空!')
              return
            }
          }
          that.form.regionCode = that.form.syndromeType === 1 ? that.form.regionCode : undefined;
          that.form.regionName = that.form.syndromeType === 1 ? this.areaList.find(v => v.id === that.form.regionCode).name : undefined;
          if (that.form.id) {
            await updateDisease(that.form);
          } else {
            await addDisease(that.form);
          }
          that.$message.success(that.form.id ? "修改成功" : "新增成功");
          that.$router.go(-1);
        }
      })
    },
    onCancel() {
      this.$router.go(-1);
    }
  },
};
</script>
